這次我們要把 「Tiled Map Editor」所做出來的硬幣,加入碰撞以及分數計算。
// loading.js
preload() {
.....
this.load.image('coin', 'assets/coin.png')
}
// game.js
create() {
.....
this.coins = this.map.createFromObjects('Coins', 'Coins', { key: 'coin' })
this.coinsGroup = new Coins(this.physics.world, this, this.coins)
.....
}
addCollisions() {
.....
// 加入 coins 的碰撞偵測
this.physics.add.overlap(
this.coinsGroup,
this.player,
this.coinsGroup.collectCoin.bind(this.coinsGroup)
)
}
// conins.js
import 'phaser'
export default class Coins extends Phaser.Physics.Arcade.StaticGroup {
constructor(world, scene, spriteArray) {
super(world, scene)
this.scene = scene
spriteArray.forEach(item => {
item.setScale(0.2).setOrigin(3, -1)
this.add(item)
})
this.refresh()
}
collectCoin(player, coin) {
this.remove(coin)
coin.destroy()
}
}
接著我們可以吃硬幣時,計算分數顯示在畫面上
// index.js
import UIScene from './Scenes/UI'
this.scene.add('UI', UIScene)
// coins.js
collectCoin(player, coin) {
this.scene.events.emit('coinCollected')
}
// ui.js
import 'phaser'
export default class UIScene extends Phaser.Scene {
constructor() {
super({ key: 'UI',active: true})
}
init() {
this.coinsCollected = 0
}
create() {
this.scoreText = this.add.text(12, 12, `Score: ${this.coinsCollected}`, {
fontSize: '20px',
fill: '#ffffff'
})
this.gameScene = this.scene.get('Game')
this.gameScene.events.on('coinCollected', () => {
this.coinsCollected++
this.scoreText.setText(`Score: ${this.coinsCollected}`)
})
}
}
今天加上在 Tiled Map Editor Blocked 所做的 coins,並加入碰撞以及分數計算。也加入之前所練習過的 text 顯示 ~~
今天就先到這裡,我們明天見。